package com.ai.module.chat.config;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import io.github.asleepyfish.config.ChatGPTProperties;
import io.github.asleepyfish.service.OpenAiProxyService;
import okhttp3.OkHttpClient;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;

/**
 * @author: MrHe
 * @create: 2024-01-09 23:21
 * @description:
 **/
@Configuration
@MapperScan("com.ai.module.**.mapper")
public class MyBatisPlusConfig {

    //
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }

    @Autowired
    private  ChatGPTProperties chatGPTProperties;

    @Bean("openaiRestTemplate")
    @Primary
    public RestTemplate  openaiRestTemplate(){

        RestTemplate restTemplate = new RestTemplate();
        HttpMessageConverters converters = SpringUtil.getBean(HttpMessageConverters.class);
        restTemplate.setMessageConverters(converters.getConverters());
        // 切换类库
        OkHttpClient okHttpClient =  OpenAiProxyService.defaultClient(chatGPTProperties, Duration.ZERO);

        restTemplate.setRequestFactory(new OkHttp3ClientHttpRequestFactory(okHttpClient));
        return restTemplate;
    }

}


